import React, {useEffect, useState} from "react";
import {Layout, Menu, MenuProps} from "antd";
import './index.scss'
import {useLocation, useNavigate} from "react-router-dom";
import Logo from "@/layouts/common/Logo.tsx";
import Tittle from "@/layouts/common/Tittle.tsx";
import {getMenus} from "@/utils/MuenUtils.tsx";
import {IMenu} from "@/api/authentication.ts";
import LoadIcon from "@/components/LoadIcon/LoadIcon.tsx";
import {HomeFilled} from "@ant-design/icons";

const {Sider} = Layout;


interface IProps {
  collapsed: boolean | undefined,
  sideCollapsedWidth: number | 80 | undefined,
  sideWidth: number | 200 | undefined,
  updateCollapsed: (value: boolean) => void,
  logoSrc: string,
  logoSize: number | 32,
  title: string,
  titleSize: number
}

type MenuItem = Required<MenuProps>['items'][number];


const LayoutSider: React.FC<IProps> = (props) => {

  const {
    collapsed,
    updateCollapsed,
    sideCollapsedWidth,
    sideWidth,
    logoSrc,
    logoSize,
    title,
    titleSize
  } = props

  const navigate = useNavigate()
  const location = useLocation()


  // openKeys 当前所有展开着的数组，一开始给空默认不展示
  const [openKeys, setOpenKeys] = useState(['']);


  const hdOpenChange = (keys: string[]) => {
    // 点击展开和收缩的时候执行这里的代码
    // console.log(keys); // 这些展开这的keys的数组
    // 设置为最后一项
    setOpenKeys([keys[keys.length - 1]]);

  }

  const menuClick: MenuProps['onClick'] = (e) => {
    const isExternal = /^(https?:|mailto:|tel:)/.test(e.key);
    if (!isExternal)
      navigate(e.key)
  }
  // 封装获取Item的方法
  const getMenuItem = (label: React.ReactNode, key: React.Key, icon?: React.ReactNode, children?: MenuItem[]): MenuItem => {
    return {key, icon, children, label,} as MenuItem;
  }
  // 组装菜单列表
  const generateMenus = (menus: Array<IMenu>): Array<MenuItem> => {

    const menuItems: MenuItem[] = []

    for (const menu of menus) {
      const currentMenu: MenuItem = getMenuItem(
        menu.isFrame === '0' ?
          <a href={menu.path} target="_blank" rel="noopener noreferrer">{menu.label}</a> : menu.label,
        menu.path || '/',
        <LoadIcon name={menu.icon && menu.icon !== '#' ? menu.icon : ''}/>,
        menu.children && menu.children.length > 0 ? generateMenus(menu.children) : undefined
      )
      menuItems.push(currentMenu)
    }

    return menuItems
  }

  const menuItems: MenuItem[] = [
    getMenuItem('首页', '/home', <HomeFilled/>),
    ...generateMenus(getMenus()),
  ]

  /**
   * 监测路由地址改变的时候，是否有父级组件，如果有，展开父级组件
   * 只适合二级路由
   */
  useEffect(() => {
    if (!collapsed) {
      const keyArr = location.pathname.split('/').filter(item => item !== '')
      if (keyArr.length === 3) {
        // console.log('/' + keyArr[0])
        setOpenKeys([...openKeys, '/' + keyArr[0]])
      }
    }
  }, [navigate, location, collapsed])


  return (
    <div>
      <Sider collapsible collapsed={collapsed} onCollapse={(value) => updateCollapsed(value)}
             style={{overflow: 'auto', height: '100vh', position: 'fixed', left: 0, top: 0, bottom: 0,backgroundColor:"#fff"}}
             width={sideWidth} collapsedWidth={sideCollapsedWidth}
             trigger={null}>
        <div className="demo-logo-vertical">
          <Logo logoSrc={logoSrc} logoSize={logoSize}/>
          <Tittle collapsed={collapsed} title={title} titleSize={titleSize}/>
        </div>
        <Menu theme="light" defaultSelectedKeys={[location.pathname]} mode="inline" items={menuItems}
              onOpenChange={hdOpenChange}
              onClick={menuClick} openKeys={openKeys}/>
      </Sider>
    </div>
  )
}

export default LayoutSider